<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { login } from "../api/api";
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
const loginForm = reactive({
    username:"",
    password:"",
})
const loginRules:FormRules = {
    username:{required:true,message:"请输入用户名",trigger:"blur"},
    password:{required:true,message:"请输入密码",trigger:"blur"},
}
const router = useRouter();
const loginRef = ref<FormInstance>();
const handleLogin = () => {
    if(loginRef.value){
        loginRef.value.validate((async valid=>{
          if(valid){
            const res = await login(loginForm);
            if(res.data.data.code === 10000){
              ElMessage.success("登陆成功");
              router.push("/dashboard");
              sessionStorage.login="yes";
            }else{
              ElMessage.error("登陆失败");
            }
          }
        }));
    }
}
</script>

<template>
  <div>
    <el-card>
      <h3>后台管理系统</h3>
      <el-form label-width="100px" :model="loginForm" :rules="loginRules" ref="loginRef">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.el-card {
  width: 700px;
  height: 400px;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
</style>
